"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true
});

// 查看是否授权
function initAppUser() {
  var that = this;

  wx.getSetting({
    success: function(res) {
      if (res.authSetting['scope.userInfo']) {
        wx.getUserInfo({
          success: function(res) {
            console.log('用户已经授权过', res.userInfo)
            //用户已经授权过
            wx.setStorageSync('userInfo', res.userInfo);
            that.setData({
              userInfo: res.userInfo
            });
            wx.showTabBar({});

            // 初始化用户信息
            initUser(that);
          }
        })
      } else {
        that.setData({
          userInfo: ''
        });
        wx.hideTabBar({});
      }
    }
  });
}

function initUser(that) {
  // var that = this;
  var HOST = getApp().globalData.HOST;
  var openid = wx.getStorageSync('openid');

  // 1. 第一次打开, 尝试创建用户
  if (!openid) {
    wx.login({
      success: function(resp) {
        console.log('wx.login:', resp)
        var code = resp.code;
        wx.request({
          url: HOST + 'openid',
          data: {
            js_code: code,
            grant_type: 'authorization_code'
          },
          method: 'get',
          success: function(resp) {
            console.log('get openid:', resp)

            var openid = resp.data.data.openid;
            var session_key = resp.data.data.session_key;

            console.log('openid', openid)
            console.log('session_key', session_key)

            // 缓存 用户信息到本地
            wx.setStorage({
              key: 'openid',
              data: openid
            });
            wx.setStorage({
              key: 'session_key',
              data: session_key
            });

            // 创建用户
            wx.request({
              url: HOST + 'user',
              method: 'post',
              data: {
                openid: openid,
                username: that.data.userInfo.nickName,
                gender: that.data.userInfo.gender
              },
              success(resp) {
                console.log('第一次创建用户:', resp);
                getGroupInfo(that, openid);
              },
            });
          }
        })
      } //
    }) //login
  } //openid
  else {
    getGroupInfo(that, openid);
  }
}

// 获取是否是团长
function getGroupInfo(that, openid) {
  // var that = this;
  var HOST = getApp().globalData.HOST;

  wx.request({
    url: HOST + 'user',
    method: 'post',
    data: {
      openid: openid
    },
    success: function(resp) {
      console.log('获取是否是团长:', resp);
      var istuan = 0;
      var tuanstatus = 0;
      if (resp.data.code == '000' && resp.data.data.length > 0) {
        istuan = 1;
        tuanstatus = resp.data.data.status;
      }
      wx.setStorage({
        key: 'istuan',
        data: istuan
      });
      wx.setStorage({
        key: 'tuanstatus',
        data: tuanstatus, // 团长状态
      });
    },
  })
}

exports.initAppUser = initAppUser;